package com.oocl.euc.core.requestform.service;

import com.oocl.euc.common.constant.MailTemplateKey;
import com.oocl.euc.common.constant.ProceduresType;
import com.oocl.euc.common.utils.EmailMarkUtil;
import com.oocl.euc.common.utils.FileUtil;
import com.oocl.euc.common.utils.StringUtil;
import com.oocl.euc.common.utils.XMLUtil;
import com.oocl.euc.core.attachment.model.Attachment;
import com.oocl.euc.core.maintenance.model.Category;
import com.oocl.euc.core.maintenance.model.EmailTemplate;
import com.oocl.euc.core.maintenance.model.SubCategory;
import com.oocl.euc.core.maintenance.model.Users;
import com.oocl.euc.core.maintenance.service.CategoryService;
import com.oocl.euc.core.maintenance.service.EmailTemplateService;
import com.oocl.euc.core.maintenance.service.SubCategoryService;
import com.oocl.euc.core.maintenance.service.UsersService;
import com.oocl.euc.core.requestform.bo.ChangeDetail;
import com.oocl.euc.core.requestform.model.RequestForm;
import com.oocl.euc.core.requestform.model.RequestFormEmailMapping;
import com.oocl.euc.core.requestform.model.RequestPostmortem;
import com.oocl.euc.core.requestform.model.RequestProcedures;
import com.oocl.euc.framework.common.email.EmailEntity;
import com.oocl.euc.framework.common.email.EmailSender;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSendException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EmailSenderService {
    public static final String FILE_SUFFIX = ".ftl";
    public static final String TEMP_DIR = "template";
    public static final String CURRENT_PATH = ".";
    public static final String FROM = " from ";
    public static final String TIME_FORMAT = "dd-MMM-yyyy HH:mm";
    private Logger logger = Logger.getLogger(EmailSenderService.class);

    @Autowired
    private UsersService usersService;
    @Autowired
    private SubCategoryService subCategoryService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    EmailTemplateService emailTemplateService;

    public void sendEmail(String emailTemplateKey, RequestForm requestForm) throws MessagingException {
        EmailTemplate template = emailTemplateService.findByEmailTempalteKey(emailTemplateKey);
        if (template != null) {
            this.send(template, requestForm);
        } else {
            throw new NullPointerException("template is not exist");
        }
    }

    public void sendEmail(String emailTemplateKey, RequestForm requestForm, List<Attachment> attList) throws MessagingException {
        EmailTemplate template = emailTemplateService.findByEmailTempalteKey(emailTemplateKey);
        if (template != null) {
            this.send(template, requestForm, attList);
        } else {
            throw new NullPointerException("template is not exist");
        }
    }

    public void send(EmailTemplate template, RequestForm requestForm) throws MessagingException {
        this.send(template, requestForm, null);
    }

    public void send(EmailTemplate template, RequestForm requestForm, List<Attachment> attList) throws MessagingException {
        EmailTemplate mappedTemplate = this.mapEmailTemplate(template, requestForm);
        if (mappedTemplate != null && needSendEmail(requestForm)) {
            this.send(mappedTemplate, attList);
        }
    }

    private void send(EmailTemplate mappedEmailTemplate, List<Attachment> attList) throws MessagingException {
        EmailEntity emailEntity = new EmailEntity();

        if ("CHGCNTL".equals(mappedEmailTemplate.getSendFrom())) {
            emailEntity.setFrom(MailTemplateKey.CHGCNTL_NO_REPLY_NAME);
        } else {
            emailEntity.setFrom(buildOneEmailAddress(mappedEmailTemplate.getSendFrom()));
        }
        String[] to = buildEmailAddress(StringUtil
                .ignoreRepeat(mappedEmailTemplate.getSendTo()));
        emailEntity.setTo(to);

        String[] cc = buildEmailAddress(StringUtil
                .ignoreRepeat(mappedEmailTemplate.getEmailCC()));
        emailEntity.setCc(cc);

        String[] bcc = buildEmailAddress(StringUtil
                .ignoreRepeat(mappedEmailTemplate.getEmailBCC()));
        emailEntity.setBcc(bcc);

        String subject = mappedEmailTemplate.getSubject();
        if (subject != null) {
            emailEntity.setSubject(subject);
        }
        String content = mappedEmailTemplate.getContent();
        if (content != null) {
            emailEntity.setContent(content.replace("startUI", "<").replace("endUI", ">"));
        }

        if (!CollectionUtils.isEmpty(attList)) {
            Map<String, File> attachmentMap = attList.stream().
                    collect(Collectors.toMap(Attachment::getFileName, attachment
                            -> FileUtil.writeByteToFile(attachment.getLocation(), attachment.getFileName(), attachment.getContent())));
            emailEntity.setAttachmentFiles(attachmentMap);
        }
        try {
            EmailSender.sendAttachmentsEmail(emailEntity);
        } catch (Exception e) {
            logger.error("Exception", e);
            if (to.length == 0 && cc.length == 0 && bcc.length == 0) {
                throw new MailSendException("email receiver is not exist");
            }
            if (mappedEmailTemplate.getSendFrom() == null || mappedEmailTemplate.getSendFrom().trim() == "") {
                throw new MailSendException("email sender is not exist");
            }
        }
    }

    public boolean needSendEmail(RequestForm pcrsForm) {
        boolean isNeed = true;
        boolean isChange = pcrsForm.getImportantFieldIsChanged() || pcrsForm.getWorkingProcedureChanged() || pcrsForm.getPpRunResultIsChanged() || pcrsForm.getQaTestingResultIsChanged();
        if (isChange && pcrsForm.getIsApprover()) {
            isNeed = false;
        }

        logger = Logger.getLogger(getClass().getName());
        logger.info("needSendEmail:" + isNeed);
        return isNeed;
    }

    private String buildOneEmailAddress(String mailString) {
        if (StringUtils.isEmpty(mailString)) {
            return "";
        }
        if (StringUtil.isEmailAddress(mailString)) {
            return mailString;
        } else {
            Users user = usersService.findByDomainId(mailString.toUpperCase());
            if (user != null && user.getEmail() != null && !user.getEmail().trim().equals(""))
                return user.getEmail();
            else if (mailString.indexOf("@") < 0) {
                return (mailString + "@exch.oocl.com").toUpperCase();
            } else {
                return mailString.toUpperCase();
            }
        }
    }

    private String[] buildEmailAddress(String mailString) {
        if (mailString == null || mailString.trim().equals("")) {
            return new String[0];
        }

        String[] mails = StringUtil.replaceSeparator(mailString).split(";");

        String[] emailAddress = (String[]) Arrays.stream(mails).distinct().map(mail -> buildOneEmailAddress(mail)).toArray(String[]::new);

        return emailAddress;
    }

    protected EmailTemplate mapEmailTemplate(EmailTemplate emailTemplate, RequestForm requestForm) {
        return this.mapEmailTemplate(emailTemplate, requestForm, null);
    }

    protected EmailTemplate mapEmailTemplate(EmailTemplate emailTemplate, RequestForm requestForm, String message) {
        String tmpName = UUID.randomUUID().toString() + FILE_SUFFIX;
        File templateFile = new File(TEMP_DIR + File.separator + tmpName);
        File templateFolder = new File(CURRENT_PATH + File.separator + TEMP_DIR);
        FileWriter out = null;
        try {
            logger = Logger.getLogger(getClass().getName());
            if (templateFolder.mkdir())
                logger.info("template file path created succesffully:" + templateFolder.getPath());
            else
                logger.info("template file path exists or met error when make dir:" + templateFolder.getPath());
            if (templateFile.createNewFile())
                logger.info("file creatd:" + templateFolder.getPath() + File.separator + templateFile.getName());

            out = new FileWriter(templateFile);
            String templateXML = XMLUtil.convertToXmlStr(emailTemplate);
            String _templateXML = templateXML.replace("startList", "<").replace("endList", ">");
            out.write(_templateXML);
            out.flush();
            RequestFormEmailMapping requestFormEmailMapping = Mapping(requestForm, message);
            if (requestFormEmailMapping != null) {
                String markedXML = EmailMarkUtil.processTemplate(templateFile.getParent(), tmpName, "UTF-8", requestFormEmailMapping);
                String _markedMXML = markedXML.replace("&lsquo;", "'").replace("&rsquo;", "'").replace("&ndash;", "–");
                EmailTemplate result = (EmailTemplate) XMLUtil.convertXmlStrToObj(EmailTemplate.class, _markedMXML);
                return result;
            } else
                return null;
        } catch (IOException e) {
            logger.error("IOException", e);
            return null;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (templateFile.delete()) {
                    logger.info("file deleted:" + templateFolder.getPath() + File.separator + templateFile.getName());
                }
                if (  templateFolder.delete()) {
                    logger.info("folder deleted:" + templateFolder.getPath());
                }
            } catch (IOException e) {
                logger.error("template service file writer close exception");
            }
        }
    }

    protected RequestFormEmailMapping Mapping(RequestForm requestForm, String message) {
        if (requestForm == null) {
            logger.warn("request form is null");
            return null;
        }

        RequestFormEmailMapping emailMapping = new RequestFormEmailMapping();

        if (requestForm.getRequestpostmortem() != null && requestForm.getRequestpostmortem().size() > 0) {
            RequestPostmortem postmortem = requestForm.getRequestpostmortem().get(
                    requestForm.getRequestpostmortem().size() - 1);
            if (postmortem.getAttendee() != null) {
                emailMapping.setPOSTMORTEM_ATTENDEE(StringEscapeUtils
                        .escapeHtml(
                                postmortem.getAttendee().replace("&", "&amp;"))
                        .replace("&ndash", "-"));
            } else {
                emailMapping.setPOSTMORTEM_ATTENDEE("");
            }
            if (postmortem.getBusinessImpact() != null) {
                emailMapping.setPOSTMORTEM_BUSINESS_IMPACT(StringEscapeUtils
                        .escapeHtml(
                                postmortem.getBusinessImpact().replace("&", "&amp;"))
                        .replace("&ndash", "-"));
            } else {
                emailMapping.setPOSTMORTEM_BUSINESS_IMPACT("");
            }
            if (postmortem.getCorrectAction() != null) {
                emailMapping.setPOSTMORTEM_CORRECT_ACTION(StringEscapeUtils
                        .escapeHtml(
                                postmortem.getCorrectAction().replace("&", "&amp;"))
                        .replace("&ndash", "-"));
            } else {
                emailMapping.setPOSTMORTEM_CORRECT_ACTION("");
            }
            if (postmortem.getPreventiveAction() != null) {
                emailMapping.setPOSTMORTEM_PREVENTIVE_ACTION(StringEscapeUtils
                        .escapeHtml(
                                postmortem.getPreventiveAction().replace("&", "&amp;"))
                        .replace("&ndash", "-"));
            } else {
                emailMapping.setPOSTMORTEM_PREVENTIVE_ACTION("");
            }
            if (postmortem.getProblem() != null) {
                emailMapping.setPOSTMORTEM_PROBLEM(StringEscapeUtils
                        .escapeHtml(
                                postmortem.getProblem().replace("&", "&amp;"))
                        .replace("&ndash", "-"));
            } else {
                emailMapping.setPOSTMORTEM_PROBLEM("");
            }
            if (postmortem.getRootCause() != null) {
                emailMapping.setPOSTMORTEM_ROOT_CAUSE(StringEscapeUtils
                        .escapeHtml(
                                postmortem.getRootCause().replace("&", "&amp;"))
                        .replace("&ndash", "-"));
            } else {
                emailMapping.setPOSTMORTEM_ROOT_CAUSE("");
            }
        }
        if (message != null)
            emailMapping.setMESSAGE(StringEscapeUtils.escapeHtml(message.trim()));

        if (emailMapping.getAPPLICATION_URL() == null || "".equals(emailMapping.getAPPLICATION_URL())) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            if (request != null) {
                String requestScheme = request.getScheme();
                String serverName = request.getServerName();
                int serverPort = request.getServerPort();
                String requestContextPath = request.getContextPath();

                if (serverPort == 80)
                    emailMapping.setAPPLICATION_URL(requestScheme + "://" + serverName + requestContextPath);
                else
                    emailMapping.setAPPLICATION_URL(requestScheme + "://" + serverName + ":" + serverPort + requestContextPath);
            }
        }

        if (requestForm.getEmail() != null) {
            emailMapping.setREQUESTER(requestForm.getRequesterDomainId());
        }
        if (requestForm.getEndorsedBy() != null) {
            emailMapping.setENDORSER(requestForm.getEndorsedBy());
        }
        if (requestForm.getEndorserList() != null) {
            emailMapping.setENDORSER_LIST(requestForm.getEndorserList());
        }
        if (requestForm.getCopyTo() != null) {
            emailMapping.setCC(requestForm.getCopyTo());
            emailMapping.setNOTIFYPERSONS(requestForm.getCopyTo());
        } else {
            emailMapping.setNOTIFYPERSONS("");
        }

        SubCategory subCategory = subCategoryService.findByCategoryIdAndSubCategoryId(requestForm.getCategoryId(), requestForm.getSubcategoryId());
        if (subCategory != null) {
            String firRequirement = subCategory.getFirRequirement();
            if (firRequirement != null && !"".equals(firRequirement)) {
                if (StringUtils.isEmpty(emailMapping.getCC())) {
                    emailMapping.setCC(firRequirement);
                } else {
                    String cc = emailMapping.getCC();

                    String[] ccArray = (String[]) ArrayUtils.addAll(firRequirement.split(";"), cc.split(";"));
                    String _cc = Arrays.stream(ccArray).distinct().collect(Collectors.joining(";"));

                    emailMapping.setCC(_cc);

                }
            }
        }

        if (requestForm.getSecondVerifier() != null) {
            emailMapping.setSECOND_VERIFIER(requestForm.getSecondVerifier());
        }
        if (requestForm.getFirstVerifier() != null) {
            emailMapping.setFIRST_VERIFIER(requestForm.getFirstVerifier());
        }
        if (requestForm.getRequestprocedures() != null) {
            List<RequestProcedures> pList = requestForm.getRequestprocedures();

            String changeRecoveryHandler = "";
            String changeVerifier = "";
            String changeExecutor = "";
            String changeWorkingStatus = "";
            for (RequestProcedures p : pList) {
                if (p.getHandledBy() == null
                        || p.getHandledBy().trim().equals("")) {
                    continue;
                }
                if (p.getProcedureType().equalsIgnoreCase(
                        ProceduresType.TYPE_RECOVERY)) {
                    changeRecoveryHandler += p.getHandledBy() + ";";
                } else if (p.getProcedureType().equalsIgnoreCase(
                        ProceduresType.TYPE_VERIFY)) {
                    changeVerifier += p.getHandledBy() + ";";
                } else if (p.getProcedureType().equalsIgnoreCase(
                        ProceduresType.TYPE_WORKING)) {
                    changeExecutor += p.getHandledBy() + ";";
                    if (p.getTaskStatus() != null && !"".equals(p.getTaskStatus()))
                        changeWorkingStatus += p.getTaskStatus() + ";";
                }
            }

            emailMapping.setCHANGE_RECOVERY_HANDLER(StringUtil.rtrim(changeRecoveryHandler, ';'));
            emailMapping.setCHANGE_VERIFIER(StringUtil.rtrim(changeVerifier, ';'));
            emailMapping.setCHANGE_EXECUTOR(StringUtil.rtrim(changeExecutor, ';'));
            emailMapping.setWORKING_STATUS(StringUtil.rtrim(changeWorkingStatus, ';'));
        }

        if (requestForm.getCategoryId() != null) {
            Category category = categoryService.findByCategoryId(requestForm
                    .getCategoryId());
            if (category != null && category.getCategoryName() != null
                    && !category.getCategoryName().trim().equals(""))
                emailMapping.setMAIN_CATEGORY(StringEscapeUtils.escapeHtml(category.getCategoryName().replace("&", "&amp;")).replace("&ndash", "-"));
            else
                emailMapping.setMAIN_CATEGORY(StringEscapeUtils.escapeHtml(requestForm.getCategoryId().replace("&", "&amp;")).replace("&ndash", "-"));

            if (requestForm.getSubcategoryId() != null) {
                if (subCategory != null) {
                    if (subCategory.getSubcategoryName() != null
                            && !subCategory.getSubcategoryName().trim()
                            .equals(""))
                        emailMapping.setSUB_CATEGORY(StringEscapeUtils.escapeHtml(subCategory.getSubcategoryName().replace("&", "&amp;")).replace("&ndash", "-"));
                    else
                        emailMapping.setSUB_CATEGORY(StringEscapeUtils.escapeHtml(requestForm.getSubcategoryId().replace("&", "&amp;")).replace("&ndash", "-"));

                    if (subCategory.getCirculationTo() != null
                            && !subCategory.getCirculationTo().trim()
                            .equals(""))
                        emailMapping
                                .setCLASSIFICATION_CIRCULATION_LIST(subCategory
                                        .getCirculationTo().trim());
                }
            }
        }

        if (requestForm.getOldCategoryName() != null && !requestForm.getOldCategoryName().trim().equals("")) {
            emailMapping.setOLD_MAIN_CATEGORY(StringEscapeUtils.escapeHtml(requestForm.getOldCategoryName().replace("&", "&amp;")).replace("&ndash", "-"));
        }

        if (requestForm.getOldSubCategoryName() != null && !requestForm.getOldSubCategoryName().trim().equals("")) {
            emailMapping.setOLD_SUB_CATEGORY(StringEscapeUtils.escapeHtml(requestForm.getOldSubCategoryName().replace("&", "&amp;")).replace("&ndash", "-"));
        }

        if (requestForm.getChangeWorkingStatusBy() != null) {
            emailMapping.setHKCTR_CHGCNTL(requestForm.getChangeWorkingStatusBy());
        }

        if (requestForm.getChangeStatusBy() != null) {
            emailMapping.setHKCTR_CHGCNTL(requestForm.getChangeStatusBy());
        }

        if (requestForm.getChangeChgcntlBy() != null) {
            emailMapping.setHKCTR_CHGCNTL(requestForm.getChangeChgcntlBy());
        }

        if (requestForm.getFirstVerificationReason() != null && !requestForm.getFirstVerificationReason().trim().equals("")) {
            emailMapping.setFIRST_VERIFICATION_ISSUE(StringEscapeUtils.escapeHtml(requestForm.getFirstVerificationReason().replace("&", "&amp;")).replace("&ndash", "-"));
        }

        if (requestForm.getFirstVerificationImpact() != null && !requestForm.getFirstVerificationImpact().trim().equals("")) {
            emailMapping.setFIRST_VERIFICATION_IMPACT(StringEscapeUtils.escapeHtml(requestForm.getFirstVerificationImpact().replace("&", "&amp;")).replace("&ndash", "-"));
        }

        if (requestForm.getVerificationReason() != null && !requestForm.getVerificationReason().trim().equals("")) {
            emailMapping.setSECOND_VERIFICATION_ISSUE(StringEscapeUtils.escapeHtml(requestForm.getVerificationReason().replace("&", "&amp;")).replace("&ndash", "-"));
        }

        if (requestForm.getVerificationImpact() != null && !requestForm.getVerificationImpact().trim().equals("")) {
            emailMapping.setSECOND_VERIFICATION_IMPACT(StringEscapeUtils.escapeHtml(requestForm.getVerificationImpact().replace("&", "&amp;")).replace("&ndash", "-"));
        }

        if (requestForm.getApproveImpactBy() != null) {
            emailMapping.setEASC(requestForm.getApproveImpactBy());
        }

        if (requestForm.getChgCtlRef() != null && !requestForm.getChgCtlRef().trim().equals("")) {
            emailMapping.setCHGCNTLMSG(StringEscapeUtils.escapeHtml(requestForm.getChgCtlRef().replace("&", "&amp;")).replace("&ndash", "-"));
        }

        if (requestForm.getRiskAssessmentReviewResult() != null) {
            emailMapping.setNEW_RA_RESULT_CHANGE(requestForm.getRiskAssessmentReviewResult());
        }
        if (requestForm.getOldRiskAssessmentReviewResult() != null && !requestForm.getOldRiskAssessmentReviewResult().equals(requestForm.getRiskAssessmentReviewResult())) {
            emailMapping.setOLD_RA_RESULT_CHANGE(requestForm.getOldRiskAssessmentReviewResult());
        }

        if (requestForm.getRiskAssessmentRemark() != null && !requestForm.getRiskAssessmentRemark().trim().equals("")) {
            emailMapping.setNEW_RA_REVIEW_CHANGE(StringEscapeUtils.escapeHtml(requestForm.getRiskAssessmentRemark().replace("&", "&amp;")).replace("&ndash", "-"));
        }
        if (requestForm.getOldRiskAssessmentRemark() != null && !requestForm.getOldRiskAssessmentRemark().equals(requestForm.getRiskAssessmentRemark())) {
            emailMapping.setOLD_RA_REVIEW_CHANGE(StringEscapeUtils.escapeHtml(requestForm.getOldRiskAssessmentRemark().replace("&", "&amp;")).replace("&ndash", "-"));
        }

        if (requestForm.getRiskAssessmentProgress() != null) {
            emailMapping.setNEW_RA_PROGRESS_CHANGE(requestForm.getRiskAssessmentProgress());
        }
        if (requestForm.getOldRiskAssessmentProgress() != null && !requestForm.getOldRiskAssessmentProgress().equals(requestForm.getRiskAssessmentProgress())) {
            emailMapping.setOLD_RA_PROGRESS_CHANGE(requestForm.getOldRiskAssessmentProgress());
        }
        if (requestForm.getRiskLevel() != null) {
            emailMapping.setNEW_RISK_LEVEL_CHANGE(requestForm.getRiskLevel());
        }
        if (requestForm.getOldRiskLevel() != null && !requestForm.getOldRiskLevel().equals(requestForm.getRiskLevel())) {
            emailMapping.setOLD_RISK_LEVEL_CHANGE(requestForm.getOldRiskLevel());
        }

        if (requestForm.getRequestStatus() != null) {
            emailMapping.setNEW_requestForm_STATUS(requestForm.getRequestStatus());
        }
        if (requestForm.getOldStatus() != null && !requestForm.getOldStatus().equals(requestForm.getRequestStatus())) {
            emailMapping.setOLD_requestForm_STATUS(requestForm.getOldStatus());
        }
        if (requestForm.getChangeObjective() != null) {
            emailMapping.setNEW_CHANGE_OBJECTIVE(StringEscapeUtils.escapeHtml(requestForm.getChangeObjective().replace("&", "&amp;")).replace("&ndash", "-"));
        }
        if (requestForm.getOldChangeObjective() != null && !requestForm.getOldChangeObjective().equals(requestForm.getChangeObjective())) {
            emailMapping.setOLD_CHANGE_OBJECTIVE(StringEscapeUtils.escapeHtml(requestForm.getOldChangeObjective().replace("&", "&amp;")).replace("&ndash", "-"));
        }

        if (requestForm.getRefNO() != null) {
            emailMapping.setREF_NO(requestForm.getRefNO());
        }
        if (requestForm.getTtNumber() != null) {
            emailMapping.setTT_NUMBER(requestForm.getTtNumber());
        }
        if (requestForm.getChangeImportantFieldsAndQAPPBy() != null) {
            emailMapping.setCHANGE_BY(requestForm.getChangeImportantFieldsAndQAPPBy());
        }

        if (requestForm.getUpdatedBy() != null) {
            emailMapping.setUPDATE_BY(requestForm.getUpdatedBy().getDomainId());
        }

        if (requestForm.getChangeClassification() != null && !requestForm.getChangeClassification().trim().equals("")) {
            emailMapping.setCHANGE_CLASSIFICATION(StringEscapeUtils.escapeHtml(requestForm.getChangeClassification().replace("&", "&amp;")).replace("&ndash", "-"));
        }
        if (requestForm.getChangeObjective() != null && !requestForm.getChangeObjective().trim().equals("")) {
            emailMapping.setCHANGE_OBJECTIVE(StringEscapeUtils.escapeHtml(requestForm.getChangeObjective().replace("&", "&amp;")).replace("&ndash", "-"));
        }
        if (requestForm.getOnlineServiceImpact() != null && !requestForm.getOnlineServiceImpact().trim().equals("")) {
            String onlineServiceImpact = StringEscapeUtils.escapeHtml(requestForm.getOnlineServiceImpact().replace("&", "&amp;")).replace("&ndash", "-");

            if (requestForm.getOnlineServiceImpactFromDate() != null) {
                DateFormat formatter = new SimpleDateFormat(TIME_FORMAT);
                String onlineServiceImpactFromDateString = "";
                String onlineServiceImpactToDateString = "";
                onlineServiceImpactFromDateString = formatter.format(requestForm.getOnlineServiceImpactFromDate());
                onlineServiceImpactToDateString = formatter.format(requestForm.getOnlineServiceImpactToDate());
                onlineServiceImpact += FROM + onlineServiceImpactFromDateString + " to " + onlineServiceImpactToDateString;
            }
            emailMapping.setONLINE_SERVICE_IMPACT(onlineServiceImpact);
        } else
            emailMapping.setONLINE_SERVICE_IMPACT("No");

        if (requestForm.getApplicationImpact() != null && !requestForm.getApplicationImpact().trim().equals(""))
            emailMapping.setAPPLICATION_FUNCTION_IMPACT(StringEscapeUtils.escapeHtml(requestForm.getApplicationImpact().replace("&", "&amp;")).replace("&ndash", "-"));
        else
            emailMapping.setAPPLICATION_FUNCTION_IMPACT("No");
        //fiona
        if ((requestForm.getOldOnlineServiceImpact() != null && !requestForm.getOldOnlineServiceImpact().trim().equals(""))
                || requestForm.getOldOnlineServiceImpactFromDate() != null
                || requestForm.getOldOnlineServiceImpactToDate() != null) {
            String oldOnlineServiceImpact = "";
            DateFormat formatter = new SimpleDateFormat(TIME_FORMAT);
            if (requestForm.getOldOnlineServiceImpact() != null && !requestForm.getOldOnlineServiceImpact().trim().equals("")) {
                oldOnlineServiceImpact += StringEscapeUtils.escapeHtml(requestForm.getOldOnlineServiceImpact().replace("&", "&amp;")).replace("&ndash", "-");
            } else {
                oldOnlineServiceImpact += StringEscapeUtils.escapeHtml(requestForm.getOnlineServiceImpact().replace("&", "&amp;")).replace("&ndash", "-");
            }

            if (requestForm.getOldOnlineServiceImpactFromDate() != null) {
                oldOnlineServiceImpact += " from " + formatter.format(requestForm.getOldOnlineServiceImpactFromDate());
            } else {
                oldOnlineServiceImpact += " from " + formatter.format(requestForm.getOnlineServiceImpactFromDate());
            }

            if (requestForm.getOldOnlineServiceImpactToDate() != null) {
                oldOnlineServiceImpact += " to " + formatter.format(requestForm.getOldOnlineServiceImpactToDate());
            } else {
                oldOnlineServiceImpact += " to " + formatter.format(requestForm.getOnlineServiceImpactToDate());
            }

            emailMapping.setOLD_ONLINE_SERVICE_IMPACT(oldOnlineServiceImpact);
        }

        if (requestForm.getOldApplicationServiceImpact() != null && !requestForm.getOldApplicationServiceImpact().trim().equals(""))
            emailMapping.setOLD_APPLICATION_SERVICE_IMPACT(StringEscapeUtils.escapeHtml(requestForm.getOldApplicationServiceImpact().replace("&", "&amp;")).replace("&ndash", "-"));

        if (requestForm.getHasOnlineServiceImpact() != null && !requestForm.getHasOnlineServiceImpact().trim().equals(""))
            emailMapping.setHAS_ONLINE_SERVICE_IMPACT(requestForm.getHasOnlineServiceImpact());

        if (requestForm.getHasApplicationImpact() != null && !requestForm.getHasApplicationImpact().trim().equals(""))
            emailMapping.setHAS_APPLICATION_IMPACT(requestForm.getHasApplicationImpact());

        if (requestForm.getOldHasOnlineServiceImpact() != null && !requestForm.getOldHasOnlineServiceImpact().trim().equals(""))
            emailMapping.setOLD_HAS_ONLINE_SERVICE_IMPACT(requestForm.getOldHasOnlineServiceImpact());

        if (requestForm.getOldHasApplicationImpact() != null && !requestForm.getOldHasApplicationImpact().trim().equals(""))
            emailMapping.setOLD_HAS_APPLICATION_IMPACT(requestForm.getOldHasApplicationImpact());

        removeWorkingProcedureAndRecoveryBlank(requestForm.getRecoveryChangeDetails());
        removeWorkingProcedureAndRecoveryBlank(requestForm.getProcedureChangeDetails());
        emailMapping.setRecoveryChangeDetails(requestForm.getRecoveryChangeDetails());
        emailMapping.setProcedureChangeDetails(requestForm.getProcedureChangeDetails());

        if (requestForm.getSystemImpact() != null && !requestForm.getSystemImpact().trim().equals(""))
            emailMapping.setSYSTEM_IMPACT(StringEscapeUtils.escapeHtml(requestForm.getSystemImpact().replace("&", "&amp;")).replace("&ndash", "-"));
        else
            emailMapping.setSYSTEM_IMPACT("No");

        if (requestForm.getRequestStatus() != null) {
            emailMapping.setREQUEST_STATUS(requestForm.getRequestStatus());
        }
        if (requestForm.getExpectedDate() != null) {
            DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
            emailMapping.setEXPECTED_DATE_CHANGE(formatter.format(requestForm
                    .getExpectedDate()));
        }
        if (requestForm.getExpectedTime() != null) {
            emailMapping.setEXPECTED_TIME_CHANGE(requestForm.getExpectedTime());
        }
        if (requestForm.getEndorsedAt() != null) {
            DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
            formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            emailMapping.setENDORSED_AT(formatter.format(requestForm.getEndorsedAt()));
        }
        if (requestForm.getOldExpectedDate() != null) {
            emailMapping.setOLD_EXPECTED_DATE_CHANGE(requestForm.getOldExpectedDate());
        }
        if (requestForm.getOldExpectedTime() != null) {
            emailMapping.setOLD_EXPECTED_TIME_CHANGE(requestForm.getOldExpectedTime());
        }
        if (requestForm.getOldPPRunResult() != null) {
            emailMapping.setOLD_PP_RUN_RESULT_CHANGE(requestForm.getOldPPRunResult());
        }
        if (requestForm.getPpTrialRunResult() != null) {
            emailMapping.setNEW_PP_RUN_RESULT_CHANGE(requestForm.getPpTrialRunResult());
        }
        if (requestForm.getOldQATestingResult() != null) {
            emailMapping.setOLD_QA_TESTING_RESULT(requestForm.getOldQATestingResult());
        }
        if (requestForm.getTestingResult() != null) {
            emailMapping.setQA_TESTING_RESULT(requestForm.getTestingResult());
        }
        if (!emailMapping.getEXPECTED_DATE_CHANGE().isEmpty() && !emailMapping.getEXPECTED_TIME_CHANGE().isEmpty()) {
            String expectedTimeChange = emailMapping.getEXPECTED_DATE_CHANGE() + " " + emailMapping.getEXPECTED_TIME_CHANGE();
            DateFormat formatter = new SimpleDateFormat(TIME_FORMAT);
            try {
                Date expectedDateChange = formatter.parse(expectedTimeChange);
                long ppConfirmationTime = expectedDateChange.getTime() - 12 * 60 * 60 * 1000;
                Date ppConfirmationDate = new Date(ppConfirmationTime);
                emailMapping.setPP_CONFIRMATION_DATE(formatter.format(ppConfirmationDate));
            } catch (ParseException e) {
                logger.error("ParseException", e);
            }

        }

        return emailMapping;
    }


    protected void removeWorkingProcedureAndRecoveryBlank(List<ChangeDetail> changeDetails) {
        if (changeDetails != null) {
            for (ChangeDetail changeDetail : changeDetails) {
                if (changeDetail.getName() != null && !changeDetail.getName().trim().equals(""))
                    changeDetail.setName(StringEscapeUtils.escapeHtml(changeDetail.getName().replace("&", "&amp;")).replace("&ndash", "-"));
                if (changeDetail.getNewValue() != null && !changeDetail.getNewValue().trim().equals(""))
                    changeDetail.setNewValue(StringEscapeUtils.escapeHtml(changeDetail.getNewValue().replace("&", "&amp;")).replace("&ndash", "-"));
                if (changeDetail.getOldValue() != null && !changeDetail.getOldValue().trim().equals(""))
                    changeDetail.setOldValue(StringEscapeUtils.escapeHtml(changeDetail.getOldValue().replace("&", "&amp;")).replace("&ndash", "-"));
            }
        }
    }

    public void setEmailTemplateService(EmailTemplateService emailTemplateService) {
        this.emailTemplateService = emailTemplateService;
    }

    public void setUsersService(UsersService usersService) {
        this.usersService = usersService;
    }

    public void setSubCategoryService(SubCategoryService subCategoryService) {
        this.subCategoryService = subCategoryService;
    }

    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }
}
